#include "wwmaintabdialog.h"
#include "ui_wwmaintabdialog.h"
#include "qtimreceiverdlg.h"
#include "tribemgrdlg.h"
#include "imlogindlg.h"
#include "filetransfermgrdlg.h"
#include "filetransferscrolldialog.h"
#include "imhistorymgrdlg.h"
#include "../Biz/WWCommonUtility.h"

#include <QCloseEvent>
#include <QDesktopServices>
#include <QMessageBox>

using namespace wwcommon;

static QString s_tab_titles[3] = {
    "Workspace",
    "Tribe Manager",
    "File Transfer Manager",
};

WWMainTabDialog::WWMainTabDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::WWMainTabDialog),
    m_im_newactivity(false),
    m_tribe_newactivity(false),
    m_filetransfer_newactivity(false),
    m_im_mgr(new QTIMReceiverDlg()),
    m_tribe_mgr(new TribeMgrDlg()),
    m_logindlg(new IMLoginDlg()),
    m_transfer_mgr(new FileTransferScrollDialog()),
    m_closeby_hand(true)
{
    ui->setupUi(this);
    Qt::WindowFlags flags = Qt::Window;
    setWindowFlags(flags | Qt::WindowCloseButtonHint|
                   Qt::WindowMinimizeButtonHint|Qt::WindowMaximizeButtonHint);

    QObject::connect(ui->tabWidget, SIGNAL(currentChanged(int)), SLOT(OnChangedTab(int)));
    QObject::connect(this, SIGNAL(initBegin()), SLOT(InitTabs()));

    emit initBegin();

    QObject::connect(m_tribe_mgr.get(), SIGNAL(tribeMemberClicked(QString)), m_im_mgr.get(), SLOT(OnSetDestUser(QString)));
    QObject::connect(m_tribe_mgr.get(), SIGNAL(tribeMemberClicked(QString)), this, SLOT(OnActiveWorkSpace(QString)));
    QObject::connect(m_im_mgr.get(), SIGNAL(newactivity()), SLOT(OnActiveWorkSpace()));
    QObject::connect(m_tribe_mgr.get(), SIGNAL(newactivity()), SLOT(OnActiveTribe()));
    QObject::connect(m_transfer_mgr.get(), SIGNAL(newactivity()), SLOT(OnActiveFileTransfer()));

    //QObject::connect(m_im_mgr.get(), SIGNAL(accepted()), SLOT(close()));
    //QObject::connect(m_im_mgr.get(), SIGNAL(rejected()), SLOT(close()));
    QObject::connect(m_im_mgr.get(), SIGNAL(immainerror()), SLOT(OnIMMainError()));

    QObject::connect(m_im_mgr.get(), SIGNAL(receiveLogout()), SLOT(OnReceiveLogout()));
    QObject::connect(m_im_mgr.get(), SIGNAL(openHistoryView()), SLOT(OnOpenHistory()));

    QObject::connect(m_tribe_mgr.get(), SIGNAL(openTribeHistory()), SLOT(OnOpenTribeHistory()));

    QObject::connect(m_logindlg.get(), SIGNAL(DoLogin(std::string, std::string, int)), m_im_mgr.get(),
                     SLOT(OnDoLogin(std::string,std::string,int)));
    QObject::connect(m_logindlg.get(), SIGNAL(rejected()), m_im_mgr.get(), SLOT(OnDoQuit()));
    QObject::connect(m_logindlg.get(), SIGNAL(accepted()), SLOT(showNormal()));
    QObject::connect(m_im_mgr.get(), SIGNAL(receiveLoginFailed(QString)),
                     m_logindlg.get(), SLOT(OnLoginFailed(QString)));
    QObject::connect(m_im_mgr.get(), SIGNAL(receiveLoginError(QString)),
                     m_logindlg.get(), SLOT(OnLoginFailed(QString)));
    QObject::connect(m_im_mgr.get(), SIGNAL(receiveLoginOK(MsgBusParam)),
                     m_logindlg.get(), SLOT(OnLoginOK(MsgBusParam)));
    QObject::connect(m_im_mgr.get(), SIGNAL(accepted()),
                     m_logindlg.get(), SLOT(reject()));

    QObject::connect(m_logindlg.get(), SIGNAL(LoginShowed()), SLOT(close()));

    // 同步处理登陆成功事件
    QObject::connect(m_im_mgr.get(), SIGNAL(notifyLoginOKUid(std::string)),
                     SLOT(OnLoginOK(std::string)), Qt::DirectConnection);

    QObject::connect(m_transfer_mgr.get(), SIGNAL(receivePicTransferFinished(MsgBusParam)), m_im_mgr.get(), SLOT(OnPicTransferFinished(MsgBusParam)));
    QObject::connect(m_transfer_mgr.get(), SIGNAL(receiveOfflineImageNotify(MsgBusParam)), m_im_mgr.get(), SLOT(OnOfflineImageNotify(MsgBusParam)));
    QObject::connect(m_transfer_mgr.get(), SIGNAL(receiveTribeImageNotify(MsgBusParam)), m_tribe_mgr.get(), SLOT(OnTribeImageNotify(MsgBusParam)));

}

WWMainTabDialog::~WWMainTabDialog()
{
    QObject::disconnect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(OnChangedTab(int)));
    delete ui;
}

void WWMainTabDialog::InitTabs()
{

    ui->tabWidget->addTab(m_im_mgr.get(), s_tab_titles[0]);
    ui->tabWidget->addTab(m_tribe_mgr.get(), s_tab_titles[1]);
    ui->tabWidget->addTab(m_transfer_mgr.get(), s_tab_titles[2]);
}

void WWMainTabDialog::InitMsgHandler()
{
    m_im_mgr->InitMsgHandler();
    m_tribe_mgr->InitMsgHandler();
    m_transfer_mgr->InitMsgHandler();
}

void WWMainTabDialog::closeEvent(QCloseEvent *e)
{
    if( (m_im_newactivity || m_tribe_newactivity || m_filetransfer_newactivity) && m_closeby_hand)
    {
        int ret = QMessageBox::question(this, "Quit Confirm", "There are some new message unreaded, you sure want to ignore them and quit?", QMessageBox::Ok|QMessageBox::Cancel);
        if(ret != QMessageBox::Ok)
        {
            e->ignore();
            return;
        }
    }
    ui->tabWidget->setCurrentIndex(0);
    //m_logindlg->setLoginErrInfo("");
    m_transfer_mgr->CleanDataOnLogout();

    m_history_mgr.reset();
    //clean old user's data
//    m_tribe_mgr->CleanDataOnLogout();
//    m_im_mgr->CleanDataOnLogout();
//    m_im_newactivity = false;
//    m_tribe_newactivity = false;
//    m_filetransfer_newactivity = false;
//    for(int i = 0; i < 3; i++)
//        ui->tabWidget->setTabText(i, s_tab_titles[i]);

    {
        e->accept();
    }
}

void WWMainTabDialog::OnIMMainError()
{
    m_closeby_hand = false;
    m_logindlg->close();
    close();
}

void WWMainTabDialog::SetWWMainUniqueFlag(const std::string& unique)
{
    m_im_mgr->SetWWMainUniqueFlag(unique);
    m_tribe_mgr->SetWWMainUniqueId(unique);
    m_transfer_mgr->SetWWMainUniqueId(unique);
}

void WWMainTabDialog::OnReceiveLogout()
{
    m_closeby_hand = false;
    close();

    if(m_logindlg->isVisible())
        return;
    m_logindlg->show();
}

void WWMainTabDialog::OnActiveWorkSpace(QString)
{
    ui->tabWidget->setCurrentIndex(0);
}

void WWMainTabDialog::OnActiveWorkSpace()
{
    if(ui->tabWidget->currentIndex() != 0)
    {
        ui->tabWidget->setTabText(0, s_tab_titles[0] + "(New Messages)");
        m_im_newactivity = true;
    }
}

void WWMainTabDialog::OnActiveTribe()
{
    if(ui->tabWidget->currentIndex() != 1)
    {
        ui->tabWidget->setTabText(1, s_tab_titles[1] + "(New Messages)");
        m_tribe_newactivity = true;
    }
}
void WWMainTabDialog::OnActiveFileTransfer()
{
    if(ui->tabWidget->currentIndex() != 2)
    {
        ui->tabWidget->setTabText(2, s_tab_titles[2] + "(New Messages)");
        m_filetransfer_newactivity = true;
    }
}

void WWMainTabDialog::OnChangedTab(int index)
{

    if(ui->tabWidget == NULL || index >= ui->tabWidget->count() || index < 0)
        return;
    ui->tabWidget->setTabText(index, s_tab_titles[index]);
    switch(index)
    {
    case 0:
        m_im_newactivity = false;
        break;
    case 1:
        m_tribe_newactivity = false;
        break;
    case 2:
        m_filetransfer_newactivity = false;
        break;
    default:
        break;
    }
}

void WWMainTabDialog::OnOpenHistory()
{
    if(m_history_mgr == NULL)
    {
        m_history_mgr.reset(new IMHistoryMgrDlg());
        QObject::connect(m_im_mgr.get(), SIGNAL(receiveHistoryData(MsgBusParam)), m_history_mgr.get(), SLOT(InitHistoryData(MsgBusParam)));
    }
    m_history_mgr->showNormal();
    QStringList allcontacts;
    m_im_mgr->GetAllContacts(allcontacts);
    m_history_mgr->InitContactList(allcontacts);
}

void WWMainTabDialog::OnOpenTribeHistory()
{
    QString tribedir = "file:///" + QString::fromStdString(FileUtility::MakeWWProfileForUser(m_im_mgr->GetLoginUserId()));
    QDesktopServices::openUrl(tribedir);
}

void WWMainTabDialog::OnLoginOK(std::string newid)
{
    if(m_oldloginuid != newid)
    {
        //clean old user's data
        m_tribe_mgr->CleanDataOnLogout();
        m_im_mgr->CleanDataOnLogout();
        m_im_newactivity = false;
        m_tribe_newactivity = false;
        m_filetransfer_newactivity = false;
        for(int i = 0; i < 3; i++)
            ui->tabWidget->setTabText(i, s_tab_titles[i]);
    }
    m_oldloginuid = newid;
    m_closeby_hand = true;
}
